//
//  AppDelegate.m
//  Faker
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "AppDelegate.h"
#import "ZGLSubscribeVC.h"
#import "ZGLHotVC.h"
#import "ZGLPlayVC.h"
#import "ZGLGuidePageCell.h"
#import <AVOSCloud/AVOSCloud.h>
#import "ZGLGuideVC.h"

@interface AppDelegate () <UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, ZGLGuidePageCellDelegate> {
    NSString *allPlist;
    NSString *isOut;
}

@property (nonatomic, strong) ZGLGuideVC *guideVC;
@property (nonatomic, strong) UIView *guideView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *subArr;
@property (nonatomic, strong) NSMutableDictionary *subDic;
@property (nonatomic, strong) NSMutableArray *tempArr;

@property (nonatomic, strong) UIButton *sureButton;
@property (nonatomic, strong) UIButton *defaultButton;

@end

@implementation AppDelegate

- (void)dealloc {
    _collectionView.delegate = nil;
    _collectionView.dataSource = nil;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        allPlist = [[NSBundle mainBundle] pathForResource:@"AllSub" ofType:@"plist"];
        NSLog(@"%@",allPlist);
        _subDic = [NSMutableDictionary dictionaryWithContentsOfFile:allPlist];
        _subArr = _subDic[@"subArr"];
        _tempArr = [self readNSUserDefaults];
    }
    return self;
}

- (void)createCollectionView {
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize  = CGSizeMake(ScaleX * 275 / 3, ScaleY * 450 / 6);
    flow.scrollDirection = 0;
    flow.minimumInteritemSpacing = 0;
    flow.minimumLineSpacing = 10;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(ScaleX * 50, ScaleY * 100, ScaleX * 275, ScaleY * 450) collectionViewLayout:flow];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerClass:[ZGLGuidePageCell class]
            forCellWithReuseIdentifier:@"AppDelegate_ZGLGuidePageCell"];
    [self.guideView addSubview:self.collectionView];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _subArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZGLGuidePageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AppDelegate_ZGLGuidePageCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.dic = _subArr[indexPath.item];
    return cell;
}
//引导页面创建过程
-(void)makeLaunchView {
    self.guideView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    UIImageView *image = [[UIImageView alloc] initWithFrame:self.guideView.frame];
    [_guideView addSubview:image];
    image.image = [UIImage imageNamed:@"ice"];
    _sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _defaultButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _guideView.backgroundColor = [UIColor whiteColor];
    [_sureButton setFrame:CGRectMake(ScaleX * 375 / 3, ScaleY * 550 , ScaleX * 375 / 3, ScaleY *40)];
    [_sureButton setTitleColor:naviColor forState:(UIControlStateSelected)];
    [_sureButton setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
    [_sureButton setTitle:@"选好啦" forState:(UIControlStateNormal)];
    [_sureButton setEnabled:NO];
    [_sureButton addTarget:self action:@selector(ok:) forControlEvents:(UIControlEventTouchUpInside)];
    _defaultButton.selected = YES;
    [_defaultButton setFrame:CGRectMake(ScaleX * 375 / 3, ScaleY * 600 , ScaleX * 375 / 3, ScaleY * 40)];
    [_defaultButton addTarget:self action:@selector(ok:) forControlEvents:(UIControlEventTouchUpInside)];
    [_defaultButton setTitleColor:naviColor forState:(UIControlStateSelected)];
    [_defaultButton setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
    [_defaultButton setTitle:@"跳过此页" forState:(UIControlStateNormal)];
    [_guideView addSubview:_sureButton];
    [_guideView addSubview:_defaultButton];
    [self.window addSubview:_guideView];
     isOut = @"YES";
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:isOut forKey:@"isOut"];
    [self createCollectionView];
}
- (void)ok:(UIButton *)button {
    if ([button.currentTitle isEqualToString:@"选好啦"]) {
        [UIView animateWithDuration:1.5 animations:^{
            _guideView.alpha = 0;//让scrollview 渐变消失
        }completion:^(BOOL finished) {
            [_guideView  removeFromSuperview];//将scrollView移除
            [self gotoMain];//进入主界面
        } ];
    } else {
        NSDictionary *dic = _subArr[0];
        _tempArr = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dict in dic[@"sons"]) {
            [_tempArr addObject:dict];
            if (_tempArr.count == 3) {
                break;
            }
        }
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:_tempArr forKey:@"currentArr"];
        [UIView animateWithDuration:1.5 animations:^{
            _guideView.alpha = 0;//让scrollview 渐变消失
        }completion:^(BOOL finished) {
            [_guideView  removeFromSuperview];//将scrollView移除
            [self gotoMain];//进入主界面
        } ];
    }
}
- (void)isOK {
    _tempArr = [self readNSUserDefaults];

    if (_tempArr.count == 0) {
        [_sureButton setEnabled:NO];
        [_defaultButton setEnabled:YES];
         _defaultButton.selected = YES;
    } else {
        _defaultButton.selected = NO;
        _sureButton.selected = YES;
        [_sureButton setEnabled:YES];
        [_defaultButton setEnabled:NO];
    }
}

//去主页
-(void)gotoMain{
#pragma 创建TabBarController
    /* 创建VC */
    /* 订阅部分 */
    ZGLSubscribeVC *subscibe = [[ZGLSubscribeVC alloc] init];
    UINavigationController *subscibeNavi = [[UINavigationController alloc]initWithRootViewController:subscibe];
    subscibeNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"S" image:[UIImage imageNamed:@"fenlei"] selectedImage:[UIImage imageNamed:@"sfenlei"]];
    /* 热点新闻部分 */
    ZGLHotVC *hot = [[ZGLHotVC alloc] init];
    UINavigationController *hotNavi = [[UINavigationController alloc]initWithRootViewController:hot];
    hotNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"H" image:[UIImage imageNamed:@"hot"] selectedImage:[UIImage imageNamed:@"shot"]];
    
    /* 玩乐部分 */
    ZGLPlayVC *play = [[ZGLPlayVC alloc] init];
    UINavigationController *playNavi = [[UINavigationController alloc]initWithRootViewController:play];
    playNavi.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"P" image:[UIImage imageNamed:@"wanle"] selectedImage:[UIImage imageNamed:@"swanle"]];
    
    UITabBarController *main = [[UITabBarController alloc] init];
    /* tabBar.viewControllers添加 */
    main.viewControllers = @[subscibeNavi, hotNavi, playNavi];
    main.selectedIndex = 0;
    /* 当前tabBar颜色 */
    main.tabBar.tintColor = [UIColor colorWithRed:1.000 green:0.100 blue:0.000 alpha:1.000];
    main.tabBar.barTintColor = naviColor;
    self.window.rootViewController = main;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [AVOSCloud setApplicationId:@"SpkhoHQzDxOPf7BykQGeJnFs"
                      clientKey:@"aEyaUvjVDIKXH8vbcbqAoKgt"];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    isOut = @"NO";
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([[defaults stringForKey:@"isOut"] isEqualToString:@"YES"]) {
        [self gotoMain];
    } else {
        self.guideVC = [[ZGLGuideVC alloc] init];
        self.window.rootViewController = self.guideVC;
        [self makeLaunchView];//为假表示没有文件，没有进入过主页
    }
    return YES;
}


//保存数据到NSUserDefaults
- (void)saveNSUserDefaultsWith:(NSString *)str;
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:str forKey:@"guideStr"];
    //这里建议同步存储到磁盘中，但是不是必须的
    [userDefaults synchronize];
}
- (id)readNSUserDefaults {
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    return [userDefaultes arrayForKey:@"currentArr"];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
